﻿using BatchQueryWebApi.Models;
using BatchQueryWebApi.Services;

namespace BatchQueryWebApi.ServicesImpl
{
    public class DeviceStatusService : IDeviceStatusService
    {
        public async Task<IEnumerable<DeviceStatusResult>> GetDeviceStatusesAsync(
            IEnumerable<string> deviceIds,
            TimeSpan timeout)
        {
            if (deviceIds == null || !deviceIds.Any())
            {
                return new List<DeviceStatusResult>();
            }

            var tasks = new List<Task<DeviceStatusResult>>();

            // 为每个设备ID创建一个查询任务
            foreach (var deviceId in deviceIds)
            {
                tasks.Add(QuerySingleDeviceStatusAsync(deviceId, timeout));
            }

            // 等待所有任务完成
            await Task.WhenAll(tasks);

            // 返回所有结果
            return tasks.Select(t => t.Result);
        }

        /// <summary>
        /// 查询单个设备状态（带超时控制）
        /// </summary>
        private async Task<DeviceStatusResult> QuerySingleDeviceStatusAsync(
            string deviceId,
            TimeSpan timeout)
        {
            var result = new DeviceStatusResult
            {
                DeviceId = deviceId,
                QueryTime = DateTime.Now
            };

            try
            {
                // 创建取消令牌源，用于超时控制
                using (var cts = new CancellationTokenSource(timeout))
                {
                    // 执行实际查询并等待结果，同时监控超时
                    var queryTask = ActualDeviceQueryAsync(deviceId, cts.Token);
                    var completedTask = await Task.WhenAny(queryTask, Task.Delay(Timeout.Infinite, cts.Token));

                    if (completedTask == queryTask)
                    {
                        // 查询成功完成
                        result.Status = await queryTask;
                        result.Success = true;
                        result.Message = "查询成功";
                    }
                    else
                    {
                        // 超时
                        result.Status = "未知";
                        result.Success = false;
                        result.Message = $"查询超时（{timeout.TotalSeconds}秒）";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Status = "错误";
                result.Success = false;
                result.Message = $"查询失败: {ex.Message}";
            }

            result.EndQueryTime = DateTime.Now;

            return result;
        }

        /// <summary>
        /// 实际的设备查询操作（模拟）
        /// </summary>
        private async Task<string> ActualDeviceQueryAsync(string deviceId, CancellationToken cancellationToken)
        {
            // 模拟网络请求延迟（随机1-6秒，用于测试超时情况）
            var delay = new Random(Guid.NewGuid().GetHashCode()).Next(1, 1000);
            await Task.Delay(delay, cancellationToken);

            // 模拟不同的设备状态
            var statuses = new[] { "在线", "离线", "维护中", "低电量", "正常" };

            return statuses[new Random(deviceId.GetHashCode()).Next(statuses.Length)];
        }
    }
}